import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MdlSnackbarService, MdlDialogService } from '@angular-mdl/core';
import { TreeNode, DynamicDialogRef, DynamicDialogConfig } from 'primeng/primeng';
@Component({
  templateUrl: './transit.component.html',
  styleUrls: ['./transit.component.scss'],
  providers: []
})
export class TransitComponent implements OnInit {
  systemUrl: string;
  loading = true;
  recId: number;
  actId: number;
  submit: boolean = true;// 防止重复提交
  opinion: string = "";
  //批转流向
  transit: any[] = [];
  //最近常用
  recentlyUsed: any[] = [];
  //选中案由参数
  selectedRecords: any = {};
  //选中批转对象
  selectedNode: TreeNode;
  constructor(
    private http: HttpClient,
    public ref: DynamicDialogRef,
    public config: DynamicDialogConfig,
    public mdlSnackbarService: MdlSnackbarService
  ) {
    this.systemUrl = config.data.systemUrl;
    this.selectedRecords = config.data.selectedRecords;
  }

  ngOnInit() {
    this.recId = this.selectedRecords[0]['rec_id'];
    this.actId = this.selectedRecords[0]['act_id'];
    this.http.get('/' + this.systemUrl + '/api/workflow/search/transit?recId=' + this.recId + '&actId=' + this.actId).subscribe(data => {
      this.loading = false;
      this.transit = data['dataMap']['trans'];
      this.recentlyUsed = data['dataMap']['choices'];
      if (this.transit.length == 1 && this.transit[0]['children'].length == 1) {
        // 如果只有一个流向，自动选中
        this.selectedNode = this.transit[0]['children'][0];
      } else if (this.recentlyUsed.length > 0) {
        // 选中最常用的批转对象
        let recent = this.recentlyUsed[0];
        this.transit.forEach(e => {
          e['children'].forEach(n => {
            if (recent.targetActDefId == e.seniorId.replace('ACT_', '')
              && recent.targetPartId == e.id.replace('H_', '')) {
              this.selectedNode = e;
              return;
            }
          })
        })
      }
    });
  }

  /** 批转 */
  save() {
    if (this.selectedNode) {
      this.submit = false;
      this.http.post('/' + this.systemUrl + '/api/workflow/transit',
        {
          'recId': this.recId,
          'actId': this.actId,
          'opinion': this.opinion,
          'nextActDefId': this.selectedNode['data']['act_def_id'],
          'nextActDefName': this.selectedNode['data']['act_def_name'],
          'nextPartType': this.selectedNode['id'].split('_')[0],
          'nextPartId': this.selectedNode['id'].split('_')[1],
          'nextPartName': this.selectedNode.label,
          'transDefId': this.selectedNode['data']['transDefId']
        }).subscribe(data => {
          this.ref.close(data);
          this.mdlSnackbarService.showToast('批转成功！')
        });
    }
  }

  /** 取消 */
  cancel() {
    this.ref.close();
  }
}
